<?php


namespace app\controller;
//将excel导入数据表示例
class UploadExcel
{
    //导入不生成二维码，用户上传内容去重，导入数据表已存在自动过滤
    public function daoru1_2(){
        set_time_limit(0);//永不超时
        $file = request()->file('file');
        try {
            // 验证文件大小，名称等是否正确50k
            validate(['file'=>['filesize'=>51200, 'fileExt'=>'csv']])->check(['file'=>$file]);
            // 将文件保存到本地
            $savename= \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
            $filePath = public_path() . 'storage/' . $savename;
            //以只读方式打开文件
            $fp = fopen($filePath,'r');
            //不要标题
            fgetcsv($fp);
            $result = [];
            $key = 0;
            while($line = fgetcsv($fp)){
                $row = eval('return '.iconv('gbk','utf-8',var_export($line,true)).';');
                if (!$row[0]) {
                    break;//不支持表格中间有空行
                }
                $result[$key]['user_name'] = $row[0];
                $result[$key]['user_phone'] = $row[1];
                $key++;
            }
            //对上传的数据去重
            $uniqueArray = array_values(array_unique($result, SORT_REGULAR));
            $valuesList = [];
            $table = "user";
            $fields = "user_name, user_phone";
            foreach ($uniqueArray as $item) {
                $valuesList[] = "('" . $item['user_name'] . "', '" . $item['user_phone'] . "')";
            }
            //如果当前的姓名 + 手机存在则忽略
            $sql = "INSERT IGNORE INTO {$table} ($fields) VALUES " . implode(", ", $valuesList);
            // dump($sql);
            // exit;
            $save = Db::execute($sql);

            if($save){
                return json(['status'=>200,'data'=>'导入成功']);
            }else{
                return json(['status'=>200,'data'=>'导入失败']);
            }
            fclose($fp); // 关闭文件指针
        } catch (ValidateException $e) {
            return json(['status'=>500,'data'=>$e->getMessage()]);
        }
    }


    //生成二维码
    //2核心，推荐每次1000条用时5秒 27%
    //当前使用INSERT IGNORE为遇到重复值则跳过
    //如果用户必须唯一，那么设置插入的字段为联合唯一索引，这样使用INSERT IGNORE可避免重复插入，
    //如果数据比较多，主键推荐bigint，因为INSERT IGNORE就算跳过也会自增主键，怕被消耗完
    public function daoru1_3(){
        set_time_limit(0);//永不超时
        echo date("Y-m-d H:i:s").'----------';
        $file = request()->file('file');
        try {
            // 验证文件大小50k，名称等是否正确
            validate(['file'=>['filesize'=>51200, 'fileExt'=>'csv']])->check(['file'=>$file]);
            // 将文件保存到本地
            $savename= \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
            $filePath = public_path() . 'storage/' . $savename;
            //以只读方式打开文件
            $fp = fopen($filePath,'r');
            //不要标题
            fgetcsv($fp);
            $result = [];
            $key = 0;
            while($line = fgetcsv($fp)){
                $row = eval('return '.iconv('gbk','utf-8',var_export($line,true)).';');
                if (!$row[0]) {
                    break;//不支持表格中间有空行
                }
                $result[$key]['submit_name'] = $row[0];
                $result[$key]['submit_phone'] = $row[1];
                $key++;
            }
            //对上传的数据去重
            $uniqueArray = array_values(array_unique($result, SORT_REGULAR));
            $valuesList = [];
            $table = "submit";
            $fields = "submit_name,submit_phone";
            foreach ($uniqueArray as $item) {
                $valuesList[] = "('" . $item['submit_name'] . "', '" . $item['submit_phone'] . "')";
            }
            //如果当前的姓名 + 手机存在则忽略
            $sql = "INSERT IGNORE INTO {$table} ($fields) VALUES " . implode(", ", $valuesList);
            $save = Db::execute($sql);
            if($save){
                $cdata = Db::table($table)->order('submit_id desc')->limit($save)->select()->toArray();
                foreach ($cdata as $v){
                    //先把二维码链接插入，后面数据插入全部成功后再生成二维码
                    $submit_code = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 2).$v['submit_id'];
                    $url = $this->qr($submit_code.'_id',md5($v['submit_id']));
                    Db::table($table)->where('submit_id',$v['submit_id'])->update([
                        'submit_code'=>$submit_code,
                        'submit_qr_url'=>$url
                    ]);
                }
                return json(['status'=>200,'data'=>"导入成功"]);
            }else{
                return json(['status'=>500,'data'=>"导入失败"]);
            }
            fclose($fp); // 关闭文件指针
        } catch (ValidateException $e) {
            return json(['status'=>500,'data'=>$e->getMessage()]);
        }
    }
    public function qr($value,$file_name){
        include_once '../extend/qrcode/phpqrcode.php';
        $errorCorrectionLevel='L';//容错级别
        $matrixPointSize = 5;//生成图片大小
        $file_dir = public_path().'qrcode';
        if(!is_dir($file_dir)){
            mkdir($file_dir,0777, true);
        }
        $filename='qrcode/'.$file_name.'.png';
        \QRcode::png($value,$filename,$errorCorrectionLevel,$matrixPointSize,2);
        $path=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$filename;
        //echo '<img src='.$path.'>';
        return $path;
    }



}